import os
import utils
import imagesize
from tqdm import tqdm


path_xml = r'/media/fang/TOSHIBA EXT/Temp/Big_M1_save2'
merge_list = ['10', '11', '12', '13', '15']


for root, dirs, files in os.walk(path_xml):
    for file in tqdm(files):
        if file.split(".")[-1] == 'xml':
            infos = utils.ReadXml(root + '/' + file)
            infos = sorted(infos, key=(lambda x: x[0]))
            infos_output = [root + '/' + file]
            for info in infos:
                infos_output.append(info)
            Rewrite = False
            for idx in range(len(infos) - 1):
                s = infos[idx][-1] + infos[idx + 1][-1]
                if s in merge_list:
                    Rewrite = True
                    info_new = [infos[idx][0], min(infos[idx][1], infos[idx + 1][1]), infos[idx + 1][2], max(infos[idx][3], infos[idx + 1][3]), s]
                    infos_output.append(info_new)

            if Rewrite:
                infos_temp = [infos_output[0]]
                for info in infos_output[1:]:
                    if info[-1] != "1":
                        infos_temp.append(info)

                w, h = imagesize.get(root + '/' + file.split(".")[0] + '.jpg')
                utils.WriteXml(infos_temp, w, h)
